package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author shkstart
 * @create 2023-01-08-23:27
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        int data = 0;
        String msg = "未知的参数来自LoginServlet";
        //1从前端拿到参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2进行非空验证
        if (!StrUtil.isBlank(username) && !StrUtil.isBlank(password)) {
//            2.1得到连接
            Connection connection = DBUtils.getConnection();
            //2.2拼接sql,得到执行器
            String sql =
                    "select * from userinfo where username = ? and password=?";
            PreparedStatement statement = connection.prepareStatement(sql);
            //2.3设置执行器，并执行
            statement.setString(1, username);
            statement.setString(2, SecureUtil.md5(password));

            ResultSet resultSet = statement.executeQuery();

           if(resultSet.next()){
               UserInfo userInfo = new UserInfo();
               userInfo.setUid(resultSet.getInt("uid"));
               userInfo.setUsername(resultSet.getString("username"));
               userInfo.setPassword(resultSet.getString("password"));
               userInfo.setNickname(resultSet.getString("nickname"));
               userInfo.setImg(resultSet.getString("img"));
               userInfo.setGit(resultSet.getString("git"));
               userInfo.setState(resultSet.getInt("state"));

               //将当前登录的用户保存到session
               //a.得到httpsession对象
               HttpSession session = req.getSession(true);//登录用true，验证用false
               //b.给session中，设置当前登录的用户
               if(session!=null){
                   session.setAttribute(AppVar.SESSION_USERINFO_KEY,userInfo);
               }
                   data = 1;
               msg="登录成功";

           } else{
                msg="用户名或密码错误";
           }


        } else {
            msg = "非法参数";
        }

        //3.将结果返回给前端
        resp.getWriter().println(
                JSONUtil.toJsonStr(
                        ResultUtils.toResult(200, data, msg)
                )
        );
    }
}
